//
//  PicturePickerController.swift
//  照片查看
//
//  Created by mac on 15/11/17.
//  Copyright © 2015年 mac. All rights reserved.
//

import UIKit
/// 可重用标识符
private let PicturePickerViewId = "PicturePickerViewId"

/// 最大选择照片数量
private let PicturePickerMaxCount = 3

class PicturePickerController: UICollectionViewController {
    /// 配图数组
    lazy var pictures = [UIImage]()
    
    /// 当前选中照片索引
    private var selectedIndex = 0
    // MARK: - 构造函数
    init() {
        let layout = PicturePickerLayout()
        
        super.init(collectionViewLayout: layout)
         //注意在 CollectionViewController 中，collectionView 不是 view
        collectionView?.backgroundColor = UIColor.whiteColor()
       
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
                self.collectionView!.registerClass(PicturePickerCell.self, forCellWithReuseIdentifier: PicturePickerViewId)

    }

    // 照片选择视图布局
    private class PicturePickerLayout: UICollectionViewFlowLayout {
        
        override func prepareLayout() {
            super.prepareLayout()
            
            let m: CGFloat = UIScreen.mainScreen().scale * 4
            let count: CGFloat = 4
            
            let w = (collectionView!.bounds.width - (count + 1) * m) / count
            
            itemSize = CGSize(width: w , height:w)
        
            sectionInset = UIEdgeInsetsMake(m, m, 0, m)
            minimumInteritemSpacing = m
            minimumLineSpacing = m
        }
   }
}

extension PicturePickerController {
    
    // MARK: UICollectionView数据源方法
    
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
          // 保证末尾有一个加号按钮，如果达到上限，不显示 + 按钮！
        return pictures.count + (pictures.count == PicturePickerMaxCount ? 0 : 1)
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PicturePickerViewId, forIndexPath: indexPath) as! PicturePickerCell
        
        //设置代理
        cell.pictureDelegate = self
        cell.image = (indexPath.item < pictures.count) ? pictures[indexPath.item] : nil
        cell.backgroundColor = UIColor.whiteColor()
        return cell
    }
    
}

extension PicturePickerController: PicturePickerCellDelegate{
    
   @objc private func picturePickerCellDidAdd(cell: PicturePickerCell)
    {
        print("添加照片")
        
        if !UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary){
            
            print("不允许访问照片")
            return
        }
        
        //记录当前用户选中照片的索引
        selectedIndex = collectionView?.indexPathForCell(cell)?.item ?? 0
        
        
        //显示照片选择器
        let picker = UIImagePickerController()
        picker.delegate = self
        //picker.allowsEditing = true
        
        presentViewController(picker, animated: true, completion: nil)
        
        
    }
    /// 删除照片
    @objc private func picturePickerCellDidRemove(cell: PicturePickerCell) {
        print("删除照片")
        //1 获取当前索引
        let indexPath = collectionView!.indexPathForCell(cell)!
        //2 判断当前索引
        if indexPath.item >= pictures.count {
            return
        }
        //删除选定的照片
        pictures.removeAtIndex(indexPath.item)
        //刷新数据
        collectionView?.deleteItemsAtIndexPaths([indexPath])
    }
    
    
}
// MARK: - UIImagePickerControllerDelegate, UINavigationControllerDelegate
extension PicturePickerController: UIImagePickerControllerDelegate, UINavigationControllerDelegate{
    
    /// 选中媒体代理方法
    ///
    /// - parameter picker: 照片选择器
    /// - parameter info:   信息字典 allowsEditing = true 适合选择头像
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {

       let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        
        let scaleImage = image.scaleToWidth(600)
        // 将图像添加到数组
        // 判断当前选中的索引是否超出数组上限
        if selectedIndex >= pictures.count {
            pictures.append(scaleImage)
        } else {
            pictures[selectedIndex] = scaleImage
        }
        
        
        print(image)
        collectionView?.reloadData()
        
        dismissViewControllerAnimated(true, completion: nil)
    
    }
   
}


//MARK - 制订协议
@objc
private protocol PicturePickerCellDelegate:NSObjectProtocol {
    
    /// 添加照片
    optional func picturePickerCellDidAdd(cell: PicturePickerCell)
    /// 删除照片
    optional func picturePickerCellDidRemove(cell: PicturePickerCell)
    
    
}



// MARK: - 照片选择 Cell
private class PicturePickerCell: UICollectionViewCell {

    /// 照片选择代理
    weak var pictureDelegate: PicturePickerCellDelegate?
   
    //照片图像
    private var image: UIImage? {
        didSet {
            addButton.setImage(image ?? UIImage(named: "compose_pic_add"), forState: UIControlState.Normal)
            removeButton.hidden = (image == nil)
        }
        
    }
    
    // MARK: - 监听方法
    /// 添加照片
    @objc private func addPhoto() {
     
        pictureDelegate?.picturePickerCellDidAdd?(self)
    }
    
    /// 删除照片
    @objc private func removePhoto() {

        pictureDelegate?.picturePickerCellDidRemove?(self)
    }
    
    // MARK: - 构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /// 设置控件
    private func setupUI() {
        // 1. 添加控件
        contentView.addSubview(addButton)
        contentView.addSubview(removeButton)
        //设置布局
        addButton.frame = bounds
        removeButton.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(contentView.snp_top)
            make.right.equalTo(contentView.snp_right)
        }

        // 3. 监听方法
        addButton.addTarget(self, action: "addPhoto", forControlEvents: .TouchUpInside)
        removeButton.addTarget(self, action: "removePhoto", forControlEvents: .TouchUpInside)
        
        //设置图片框的填充模式
        addButton.imageView?.contentMode = .ScaleAspectFill
    }
    // MARK: - 懒加载控件
    /// 添加照片按钮  
   
    private lazy var addButton :UIButton = UIButton(imageName: "compose_pic_add", backImageName: nil)
    /// 删除按钮
    private lazy var removeButton:UIButton = UIButton(imageName: "compose_photo_close", backImageName: nil)
}

